package com.ctsi.config;

import com.ctsi.common.ErrorCode;
import com.ctsi.common.ResultVO;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * @description:
 * @projectName:demoActivit
 * @see:com.ctsi.config
 * @author:黎彬
 * @createTime:2021/4/8 11:04
 * @version:1.0
 * 全局异常处理
 */
@RestControllerAdvice
@ResponseBody
@Slf4j
public class RestExceptionHandler {
    private static Logger logger = LoggerFactory.getLogger(RestExceptionHandler.class);

    @ExceptionHandler(Exception.class)
    public ResultVO handleException(Exception e) {
        logger.error("系统繁忙，请稍候再试", e);
        return ResultVO.error("系统繁忙，请稍候再试", ErrorCode.SYSTEM_ERROR.getCode());
    }

    @ExceptionHandler(HttpMessageNotReadableException.class)
    public ResultVO handleHttpMessageNotReadableException(HttpMessageNotReadableException e) {
        logger.error("参数解析失败", e);
        return ResultVO.error(ErrorCode.PARAMETER_ERROR);
    }

    @ExceptionHandler(AccessDeniedException.class)
    public ResultVO AccessDeniedException(AccessDeniedException e) {
        logger.error("没有该权限",e);
        return ResultVO.error(ErrorCode.NOT_JURISDICTION);
    }

    @ExceptionHandler(InsufficientAuthenticationException.class)
    public ResultVO InsufficientAuthenticationException(InsufficientAuthenticationException e) {
        logger.error("请授权",e);
        return ResultVO.error(ErrorCode.AUTHENTICATION);
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResultVO exceptionHandler(MethodArgumentNotValidException e)
    {
        String message = e.getBindingResult().getFieldError().getDefaultMessage();
        logger.error(message);
        return ResultVO.error(message);
    }
}
